package geekbang.single;

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xuyanqing
 * @description 线程唯一单例，“线程唯一”指的是线程内唯一，线程间可以不唯一
 * @date 2025-10-13 11:52
 * @creed where there is a will,there is a way. yx
 */

public class IdGeneratorThread {

    /**
     * key 是线程 ID，value 是对象。不同的线程对应不同的对象，同一个线程只能对应一个对象
     */
    private static final ConcurrentHashMap<Long, IdGeneratorThread> instances = new ConcurrentHashMap<>();
    private IdGeneratorThread() {
    }
    public static IdGeneratorThread getInstance() {
        long currentThreadId = Thread.currentThread().getId();
        instances.putIfAbsent(currentThreadId, new IdGeneratorThread());
        return instances.get(currentThreadId);
    }
    private final AtomicInteger id = new AtomicInteger(0);
    public long getId() {
        return id.incrementAndGet();
    }
    public static void main(String[] args) {
        Random random = new Random();
        int i = random.nextInt(3) + 1;
        System.out.println(i);
    }

}
